package com.itheima.service.db.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.domain.db.AnalysisByDay;
import com.itheima.domain.db.Objectt;
import com.itheima.domain.db.TuBiao;
import com.itheima.domain.vo.AnalysisSummaryVo;
import com.itheima.mapper.AnalysisByDayMapper;
import com.itheima.mapper.LogMapper;
import com.itheima.service.db.AnalysisByDayService;
import com.itheima.util.ComputeUtil;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class AnalysisByDayServiceImpl implements AnalysisByDayService {

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;
    @Autowired
    private LogMapper logMapper;
    /**
     * 1.查询是否有今日数据
     * //注意: 数据都是从日志表中查询出来的
     * 2.如果有 创建对象 更新数据
     * 3.如果没有 创建对象 添加数据
     */
    @Override
    public void saveOrUpdate() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("record_date" , DateUtil.today());

        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        String today = DateUtil.today();
        //1.查询是否有今日数据
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(queryWrapper);




        Integer numRegistered =  logMapper.selectByType("0102" , today  );//查询今日新增用户数
        Integer numActive =  logMapper.selectNumActive( today );//活跃用户数
        Integer numLogin =  logMapper.selectByType("0101" , today);//登录次数
        Integer numRetention1d =  logMapper.selectNumRetention1d( today ,  yesterday);//次日留存
        if(analysisByDay == null){
            //2.创建对象 保存
            analysisByDay = new AnalysisByDay();
            analysisByDay.setCreated(new Date());//创建时间
            analysisByDay.setRecordDate(new Date()); // 今日日期
            analysisByDay.setNumRegistered(numRegistered); //新注册用数
            analysisByDay.setNumActive(numActive); //活跃用户数
            analysisByDay.setNumLogin(numLogin); // 登录次数
            analysisByDay.setNumRetention1d(numRetention1d);//次日留存
            analysisByDayMapper.insert(analysisByDay);
        }else{
            //3.修改数据
            analysisByDay.setCreated(new Date());//创建时间
            analysisByDay.setRecordDate(new Date()); // 今日日期
            analysisByDay.setNumRegistered(numRegistered); //新注册用数
            analysisByDay.setNumActive(numActive); //活跃用户数
            analysisByDay.setNumLogin(numLogin); // 登录次数
            analysisByDay.setNumRetention1d(numRetention1d);//次日留存
            analysisByDayMapper.updateById(analysisByDay);
        }

    }

    /**
     * 概要统计
     * 1.创建
     * 4.寻找数据来源
     * 3.赋值
     * 2.返回
     * @return
     */
    @Override
    public AnalysisSummaryVo summary() {
        //1.创建
        AnalysisSummaryVo vo = new AnalysisSummaryVo();

        //4.寻找数据
        //4.1 查询昨天和今天两条数据
        String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        String today = DateUtil.today();
        //今日数据
        QueryWrapper queryWrapper1= new QueryWrapper();
        queryWrapper1.eq("record_date" , today);
        AnalysisByDay todayAnalysisByDay = analysisByDayMapper.selectOne(queryWrapper1);
        //昨日数据
        QueryWrapper queryWrapper2= new QueryWrapper();
        queryWrapper2.eq("record_date" , yesterday);
        AnalysisByDay yesterdayAnalysisByDay = analysisByDayMapper.selectOne(queryWrapper2);



        Long count1 = analysisByDayMapper.sumCumulativeUsers();//累计用户数
        //查询活跃用户
        String beginDate = DateUtil.offsetDay(new Date(), -30).toString("yyyy-MM-dd");
        Long count2 = analysisByDayMapper.selectActiveByTime(beginDate , today);
        beginDate = DateUtil.offsetDay(new Date(), -7).toString("yyyy-MM-dd");
        Long count3 = analysisByDayMapper.selectActiveByTime(beginDate , today);

        //3.赋值
        vo.setCumulativeUsers(count1);//累计用户数
        vo.setActivePassMonth(count2);//过去30天活跃用户数
        vo.setActivePassWeek(count3);//过去7天活跃用户数
        vo.setNewUsersToday(todayAnalysisByDay.getNumRegistered().longValue());//今日新增用户数量
        BigDecimal bigDecimal = ComputeUtil.computeRate(todayAnalysisByDay.getNumRegistered(), yesterdayAnalysisByDay.getNumRegistered());
        vo.setNewUsersTodayRate(bigDecimal);//今日新增用户涨跌率，单位百分数，正数为涨，负数为跌   BigDecimal : 商业数字格式

        vo.setLoginTimesToday(todayAnalysisByDay.getNumLogin().longValue());//今日登录次数
        BigDecimal bigDecimal2 = ComputeUtil.computeRate(todayAnalysisByDay.getNumLogin(), yesterdayAnalysisByDay.getNumLogin());
        vo.setLoginTimesTodayRate(bigDecimal2);//今日登录次数涨跌率，单位百分数，正数为涨，负数为跌


        vo.setActiveUsersToday(todayAnalysisByDay.getNumActive().longValue());//今日活跃用户数量
        BigDecimal bigDecimal3 = ComputeUtil.computeRate(todayAnalysisByDay.getNumActive(), yesterdayAnalysisByDay.getNumActive());
        vo.setActiveUsersTodayRate(bigDecimal3);//今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
        //2.返回
        return vo;
    }

    //图表统计
    @Override
    public TuBiao tongji(Long sd, Long ed, String type){
        //查询今年用户
        //转换时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String start = simpleDateFormat.format(new Date(Long.valueOf(sd)));
        String end = simpleDateFormat.format(new Date(Long.valueOf(ed)));
        //查询数据从数据库
        List<AnalysisByDay> analysisByDayList = analysisByDayMapper.selectByTime(start,end);
        List<Objectt> thisYear = new ArrayList<>();
        TuBiao tuBiao = new TuBiao();

        if (CollectionUtil.isNotEmpty(analysisByDayList)) {
            //今年数据
            for (AnalysisByDay analysisByDay : analysisByDayList) {
                if (analysisByDay != null) {
                    switch (type) {
                        case "101":{
                            Objectt objectt = new Objectt();
                            objectt.setTitle(analysisByDay.getRecordDate().toString());//赋值title
                            objectt.setAmount(analysisByDay.getNumRegistered());//赋值amount
                            thisYear.add(objectt);//放到集合中
                        }
                        case "102":{
                            Objectt objectt = new Objectt();
                            objectt.setTitle(analysisByDay.getRecordDate().toString());
                            objectt.setAmount(analysisByDay.getNumActive());
                            thisYear.add(objectt);
                        }
                        case "103":{
                            Objectt objectt = new Objectt();
                            objectt.setTitle(analysisByDay.getRecordDate().toString());
                            objectt.setAmount(analysisByDay.getNumRetention1d());
                            thisYear.add(objectt);
                        }
                    }
                }
            }

            //查询去年数据
            String startLast = DateUtil.offset(new Date(Long.valueOf(sd)), DateField.DAY_OF_YEAR, -1).toString();
            String endLast = DateUtil.offset(new Date(Long.valueOf(ed)), DateField.DAY_OF_YEAR, -1).toString();
            List<AnalysisByDay> analysisByDayList2 = analysisByDayMapper.selectByTime(startLast,endLast);
            List<Objectt> lastYear = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(analysisByDayList2)) {
                for (AnalysisByDay analysisByDay : analysisByDayList2) {
                    if (analysisByDay != null) {
                        switch (type) {
                            case "101":{
                                Objectt objectt = new Objectt();
                                objectt.setTitle(analysisByDay.getRecordDate().toString());
                                objectt.setAmount(analysisByDay.getNumRegistered());
                                lastYear.add(objectt);
                            }
                            case "102":{
                                Objectt objectt = new Objectt();
                                objectt.setTitle(analysisByDay.getRecordDate().toString());
                                objectt.setAmount(analysisByDay.getNumActive());
                                lastYear.add(objectt);
                            }
                            case "103":{
                                Objectt objectt = new Objectt();
                                objectt.setTitle(analysisByDay.getRecordDate().toString());
                                objectt.setAmount(analysisByDay.getNumRetention1d());
                                lastYear.add(objectt);
                            }
                        }
                    }
                }
            }

            tuBiao.setThisYear(thisYear);//赋值thisyear
            tuBiao.setLastYear(lastYear);//赋值lastyear
        }



        return tuBiao;
    }
}
